import { Entity, Column, ManyToMany, BeforeInsert, JoinTable } from 'typeorm'
import { CommonEntity } from '@/modules/common/entities/common.entities'
import { RoleEntity } from '@/modules/role/entities/role.entity'
import * as bcrypt from 'bcrypt'
import { Exclude } from 'class-transformer'
import { TimestampTransformer } from '@/shared/transformer/timestamp.transformer'

@Entity('auth_users')
export class UserEntity extends CommonEntity {
  /**
   * 检测密码是否一致
   * @param old 加密前密码
   * @param repeat 加密后密码
   */
  static async comparePassword(old, repeat) {
    return bcrypt.compareSync(old, repeat)
  }

  // 加密
  static encryptPassword(password) {
    return bcrypt.hashSync(password, 10)
  }

  @Column({ name: 'city_id', comment: '城市code' })
  cityId: string

  @Column({ comment: '登录名' })
  username: string

  @Column({ name: 'nick_name', comment: '昵称', nullable: true })
  nickName: string

  @Column({ comment: '用户状态', width: 1 })
  status: number

  @Column({
    comment: '密码',
    nullable: true, // 因为此属性后来才加，不设置nullable无法新增此属性
    length: 100,
  })
  @Exclude({ toPlainOnly: true })
  @Column({ select: false })
  password: string

  // 加密盐
  @Column({ comment: '加密盐' })
  salt: string

  @Column({ comment: '邮箱', length: 50, nullable: true, unique: true })
  email: string

  @Column({ comment: '手机号', unique: true, nullable: true })
  phone: string

  @Column({ comment: '性别' })
  sex: string

  @Column({ comment: '生日', transformer: new TimestampTransformer() })
  birthday: string

  @Column({ name: 'customer_level', comment: '等级' })
  customerLevel: string

  @ManyToMany((type) => RoleEntity, (role) => role.users)
  @JoinTable({
    name: 'auth_user_roles',
    joinColumns: [{ name: 'user_id' }],
    inverseJoinColumns: [{ name: 'role_id' }],
  })
  roles: RoleEntity[]

  @Column('int', {
    name: 'app_id',
    nullable: true,
    comment: '应用id',
    unsigned: true,
  })
  appId: number | null

  // 插入数据前，对密码进行加密
  @BeforeInsert()
  encrypt() {
    this.password = bcrypt.hashSync(this.password, 10)
  }
}
